import React, { FC } from 'react';
import {
  FormPanel,
  FormPanelType,
  RuleType,
  MinioUploadListType,
  type FormPanelObject,
  FormPanelStatus,
  InputType,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
} from 'lfun-bg-comp';
import _ from 'lodash';
import './index.less';
import { Button, message, Modal } from 'antd';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { ECONOMIC_ATTRIBUTES, ETHNIC_ATTRIBUTES, TOWN_NATURE } from '@/constant/schoolOptions';
import AddLeader from './addLeader';
import utils, { getPathRoot } from '@/utils';
import { YES_NO } from '@/constant/basicOptions';
import ChangePopup from '@/view/component/changePopup';
import { INSTITUTION_TYPE } from '@/constant/institutionOptions';
import { openInstitution, updateInstitution } from '@/service/unit/institution';
import OpenModal from '../component/openModal';
import useCountry from '@/hooks/useCountry';
// eslint-disable-next-line react/require-default-props
const Groups: FC<{ isEdit?: boolean; value?: any; buttons?: any[] }> = ({ isEdit = false, value, buttons = [] }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [formPanelObject, setFormPanelObject] = React.useState<any>({});
  const [showChangePopup, setShowChangePopup] = React.useState(false);
  const [beforValue, setBeforValue] = React.useState<any>({});
  const { id } = useParams();
  const [showOpenComfirm, setShowOpenComfirm] = React.useState(false);
  const country = useCountry();
  const [curvalue, setCurvalue] = React.useState<any>(value);

  React.useEffect(() => {
    console.log(value, '============>>>>');
    setBeforValue(value);
    if (value && /\d+/ig.test(value['institution_communication.related_license_upload'])) {
      value['institution_communication.related_license_upload'] = [{
        uid: parseInt(value['institution_communication.related_license_upload']),
        url: value['institution_communication.related_license_upload_url'],
        name: value['institution_communication.related_license_upload_url'].split('?')[0],
      }]
    } else if (value){
      delete value['institution_communication.related_license_upload'];
      delete value['institution_communication.related_license_upload_url'];
    }
    setCurvalue(value);
  }, [value]);

  const list: FormPanelType[] = [
    {
      title: '基本信息',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '单位名称',
          name: 'institution_baseinfo.institution_name',
          key: 'institution_baseinfo.institution_name',
          required: true,
          canEdit: false,
        },
        {
          label: '机构类型',
          name: 'institution_baseinfo.institution_category',
          key: 'institution_baseinfo.institution_category',
          required: true,
          renderOption: INSTITUTION_TYPE,
          inputType: InputType.select,
        },
        {
          label: '单位英文名',
          name: 'institution_baseinfo.institution_en_name',
          key: 'institution_baseinfo.institution_en_name',
          //required: true,
          textRange: [0, 50],
        },
        // {
        //   label: '单位类型',
        //   name: 'institution_baseinfo.institution_type',
        //   key: 'institution_baseinfo.institution_type',
        //   required: true,
        //   inputType: InputType.select,
        //   renderOption: SCHOOL_ORG_TYPE,
        // },
        // {
        //   label: '行政属地',
        //   name: 'institution_baseinfo.borough',
        //   key: 'institution_baseinfo.borough',
        //   inputType: InputType.select,
        //   renderOption: SY_ZONES,
        // },
        // {
        //   label: '负责人',
        //   name: 'institution_baseinfo.party_leader_name',
        //   key: 'institution_baseinfo.party_leader_name',
        //   textRange: [0, 20],
        //   required: true,
        // },
        {
          label: '机构代码',
          name: 'institution_baseinfo.institution_code',
          key: 'institution_baseinfo.institution_code',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '统一社会信用代码',
          name: 'institution_baseinfo.social_credit_code',
          key: 'institution_baseinfo.social_credit_code',
          required: true,
          textRange: [0, 18],
        },
        
        {
          label: '是否实体',
          name: 'institution_baseinfo.is_entity',
          key: 'institution_baseinfo.is_entity',
          //required: true,
          inputType: InputType.radio,
          renderOption: YES_NO,
        },
       
        {
          label: '网址',
          name: 'institution_baseinfo.website_url',
          key: 'institution_baseinfo.website_url',
          ruleType: RuleType.url,
        },
        {
          label: '所在地城乡性质',
          name: 'institution_baseinfo.urban_rural_nature',
          key: 'institution_baseinfo.urban_rural_nature',
          inputType: InputType.cascader,
          renderOption: TOWN_NATURE,
          formatSubmitValue: value => {
            if (_.isArray(value)) {
              return value.join(',');
            }
            return value;
          },
          formatValue: value => {
            if (_.isString(value)) {
              return value.split(',');
            }
            return value;
          },
        },
        {
          label: '所在地经济属性',
          name: 'institution_baseinfo.location_economic_attribute',
          key: 'institution_baseinfo.location_economic_attribute',
          inputType: InputType.select,
          renderOption: ECONOMIC_ATTRIBUTES,
        },
        {
          label: '所在地民族属性',
          name: 'institution_baseinfo.urban_ethnic_nature',
          key: 'institution_baseinfo.urban_ethnic_nature',
          inputType: InputType.select,
          renderOption: ETHNIC_ATTRIBUTES,
        },
        {
          label: '法人证书号',
          name: 'institution_baseinfo.leg_repr_certificatenumber',
          key: 'institution_baseinfo.leg_repr_certificatenumber',
          required: true,
          textRange: [0, 50],
        },
        
      ],
    },
    {
      title: '通讯信息',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '所在地区',
          name: 'institution_communication.loc_area',
          key: 'institution_communication.loc_area',
          required: true,
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '详细地址',
          name: 'institution_communication.detailed_address',
          key: 'institution_communication.detailed_address',
          required: true,
          textRange: [0, 100],
        },
        {
          label: '联系电话',
          name: 'institution_communication.contact_number',
          key: 'institution_communication.contact_number',
          textRange: [0, 20],
        },
        {
          label: '邮政编码',
          name: 'institution_communication.postal_code',
          key: 'institution_communication.postal_code',
          ruleType: RuleType.cnPostalCode,
        },
        {
          label: '法定代表人',
          name: 'institution_communication.leg_repr_name',
          key: 'institution_communication.leg_repr_name',
          textRange: [0, 20],
          required: true,
        },
        
        {
          label: '党组织负责人姓名',
          name: 'institution_communication.party_leader_name',
          key: 'institution_communication.party_leader_name',
        },
        {
          label: '党组织负责人职务',
          name: 'institution_communication.party_leader_position',
          key: 'institution_communication.party_leader_position',
        },
        {
          label: '行政负责人姓名',
          name: 'institution_communication.adm_leader_name',
          key: 'institution_communication.adm_leader_name',
        },
        {
          label: '行政负责人职务',
          name: 'institution_communication.adm_leader_position',
          key: 'institution_communication.adm_leader_position',
        },
        {
          label: '电子邮箱',
          name: 'institution_communication.email',
          key: 'institution_communication.email',
          ruleType: RuleType.email,
        },
        {
          label: '所在经度',
          name: 'institution_communication.long',
          key: 'institution_communication.long',
          inputProps: {
            placeholder: '请输入所在经度 如经度123.4',
          },
          textRange: [0, 10],
        },
        {
          label: '所在纬度',
          name: 'institution_communication.lat',
          key: 'institution_communication.lat',
          inputProps: {
            placeholder: '请输入所在纬度 如纬度41.7',
          },
          textRange: [0, 10],
        },
        {
          label: '传真电话',
          name: 'institution_communication.fax_number',
          key: 'institution_communication.fax_number',
          textRange: [0, 20],
        },
        {
          label: '相关证照上传',
          name: 'institution_communication.related_license_upload',
          key: 'institution_communication.related_license_upload',
          required: false,
          span: 24,
          inputType: InputType.minioUpload,
          props: {
            labelCol: { span: 2 },
            wrapperCol: { span: 22 },
          },
          inputProps: {
            listType: MinioUploadListType.picture,
            text: '浏览',
            maxCount: 1,
            uploadSrv: '/school/v1/storage/school-upload-uri',
          },
          formatSubmitValue: (value: any) => {
            if (_.isArray(value) && value.length) {
              return `${value[0].uid}`;
            }
            return '';
          }
          
        },
      ]
    },
    {
      title: '领导信息',
      inputs: [
        {
          label: '',
          name: 'leader_list',
          key: 'key_51',
          span: 24,
          inputType: 'children',
          inputProps: {
            message: '领导信息未添加',
          },
          props: {
            labelCol: { span: 0 },
            wrapperCol: { span: 24 },
          },
          children: <AddLeader isEdit={isEdit} />,
        },
      ],
    },
  ];
  const save = async (hashmsg: any = true, val: any = {}) => {
    if (hashmsg) utils.showLoading();
    const params = utils.unflattenObject(formPanelObject.getFieldsValue());
    params.institution_baseinfo.id = id;
    params.institution_baseinfo = {
      ...params.institution_baseinfo,
      ...val,
    };
    const res = await updateInstitution(params);
    debugger;
    if (res.success) {
      if (hashmsg) {
        message.success('修改成功');
      } else {
        return true;
      }
    } else {
      formPanelObject.reVaildation(res);
    }
    if (hashmsg) utils.hideLoaing(res.success);
    return res.success;
  };

  const buildBtns = () => {
    return isEdit
      ? [
          <Button key="default" onClick={save}>
            保存
          </Button>,
        ]
      : buttons;
  };
  return (
    <>
      <ChangePopup
        show={showChangePopup}
        onCancel={() => setShowChangePopup(false)}
        onOk={async () => {
          const success = await save(false);
          if (success) {
            message.success('变更成功');
            setBeforValue(formPanelObject.getFieldsValue());
            setShowChangePopup(false);
          } else message.error('变更失败');
        }}
        beforValue={beforValue}
        form={formPanelObject}
        template={list}
      />
      <FormPanel
        template={list}
        key={1}
        onLoad={(formPanelObject: FormPanelObject) => {
          setFormPanelObject(formPanelObject);
        }}
        onFinishFailedDone={() => {
          document.querySelector('.ant-layout-content').scrollTop -= 80;
        }}
        onFinish={async (formPanelObject: FormPanelObject) => {
          // if (save(false)) {
          //   const res = await openInstitution(location.state.id, formPanelObject.getFieldsValue());
          //   if (res.success) {
          //     message.success('正式开办成功');
          //     navigate(`${getPathRoot()}/institution/sy`); // todo: 这里要区分行政/事业单位
          //   } else {
          //     formPanelObject.reVaildation(res);
          //   }
          // }
          setShowOpenComfirm(true);
        }}
        values={curvalue}
        btnsAlign={FormPanelBtnAlign.center}
        buttonsDisplay={FormPanelBtnDisplay.block}
        restBtnText="返回"
        submitBtnText="正式开办"
        formStatus={isEdit ? FormPanelStatus.edit : FormPanelStatus.nonEdit}
        titleStyle="shrink"
        onReset={() => {
          navigate(`${getPathRoot()}/institution/${window.location.pathname.indexOf('/xz/') !== -1 ? 'xz' : 'sy'}`); // todo: 这里要区分行政/事业单位
          return false;
        }}
        buttons={buildBtns()}
      />
      <OpenModal
        show={showOpenComfirm}
        onCancel={() => setShowOpenComfirm(false)}
        onOk={async val => {
          if (save(false, val)) {
            const res = await openInstitution(id, utils.unflattenObject(formPanelObject.getFieldsValue()));
            if (res.success) {
              message.success('正式开办成功');
              navigate(`${getPathRoot()}/institution/sy`); // todo: 这里要区分行政/事业单位
            } else {
              formPanelObject.reVaildation(res);
            }
          }
        }}
      />
    </>
  );
};

export default Groups;
